<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品信息表单</title>
    
    <!-- Vuetify 3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.0.96/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.css" rel="stylesheet">
    
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
    <!-- Vuetify 3 JS -->
    <script src="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.js"></script>
</head>
<body>
    <div id="app">
        <v-app>
            <!-- 管理员侧边栏（仅管理员可见） -->
            {% if is_admin %}
            <v-navigation-drawer v-model="drawer" app>
                <v-list nav>
                    <v-list-item title="仪表板" prepend-icon="mdi-view-dashboard"></v-list-item>
                    <v-list-item title="用户管理" prepend-icon="mdi-account"></v-list-item>
                    <v-list-item title="产品管理" prepend-icon="mdi-package-variant"></v-list-item>
                    <v-list-item title="系统设置" prepend-icon="mdi-cog"></v-list-item>
                </v-list>
            </v-navigation-drawer>
            {% endif %}
            
            <!-- 顶部应用栏 -->
            <v-app-bar app color="primary">
                {% if is_admin %}
                <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
                {% endif %}
                <v-toolbar-title>产品信息管理</v-toolbar-title>
                <v-spacer></v-spacer>
                <v-btn icon>
                    <v-icon>mdi-account</v-icon>
                </v-btn>
            </v-app-bar>

            <!-- 主内容区域 -->
            <v-main>
                <v-container>
                    <v-card class="mx-auto" max-width="800">
                        <v-card-title class="text-h5">
                            <v-icon start>mdi-file-document-edit</v-icon>
                            产品信息表单
                        </v-card-title>
                        
                        <v-card-text>
                            <v-form ref="form">
                                <v-row>
                                    <!-- 切换开关 -->
                                    <v-col cols="12">
                                        <v-radio-group
                                            v-model="isNewProduct"
                                            inline
                                            @change="onRadioChange"
                                        >
                                            <v-radio
                                                :label="isNewProduct ? '新建产品模式' : '新建产品'"
                                                :value="true"
                                            ></v-radio>
                                            <v-radio
                                                :label="!isNewProduct ? '选择现有产品' : '选择现有产品模式'"
                                                :value="false"
                                            ></v-radio>
                                        </v-radio-group>
                                    </v-col>
                                    
                                    <!-- 第一个输入框（产品编码） -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.field1"
                                            label="产品编码 *"
                                            :disabled="!isNewProduct"
                                            :rules="field1Rules"
                                            variant="outlined"
                                            @input="onFieldChange('field1', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 下拉框（仅在非新建模式下可用） -->
                                    <v-col cols="12" md="6">
                                        <v-select
                                            v-model="selectedCode"
                                            :items="codeOptions"
                                            label="选择产品 *"
                                            item-title="text"
                                            item-value="value"
                                            variant="outlined"
                                            :disabled="isNewProduct"
                                            @update:modelValue="onCodeSelect"
                                            clearable
                                        ></v-select>
                                    </v-col>
                                    
                                    <!-- 第二个输入框（产品名称） -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.field2"
                                            label="产品名称 *"
                                            variant="outlined"
                                            :rules="field2Rules"
                                            @input="onFieldChange('field2', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 第三个输入框（规格参数） -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.field3"
                                            label="规格参数"
                                            variant="outlined"
                                            @input="onFieldChange('field3', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 第四个输入框（重量） -->
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="formData.field4"
                                            label="重量(kg)"
                                            type="number"
                                            step="0.01"
                                            variant="outlined"
                                            @input="onFieldChange('field4', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 第五个输入框（价格） -->
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="formData.field5"
                                            label="价格(¥)"
                                            type="number"
                                            step="0.01"
                                            variant="outlined"
                                            @input="onFieldChange('field5', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 第六个输入框（分类） -->
                                    <v-col cols="12" md="4">
                                        <v-text-field
                                            v-model="formData.field6"
                                            label="产品分类"
                                            variant="outlined"
                                            @input="onFieldChange('field6', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 日期选择器 -->
                                    <v-col cols="12" md="6">
                                        <v-menu>
                                            <template v-slot:activator="{ props }">
                                                <v-text-field
                                                    v-model="formData.date_field"
                                                    label="生产日期"
                                                    prepend-icon="mdi-calendar"
                                                    readonly
                                                    v-bind="props"
                                                    variant="outlined"
                                                ></v-text-field>
                                            </template>
                                            <v-date-picker
                                                v-model="formData.date_field"
                                                @update:modelValue="onDateChange"
                                            ></v-date-picker>
                                        </v-menu>
                                    </v-col>
                                </v-row>
                            </v-form>
                        </v-card-text>
                        
                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn 
                                color="secondary" 
                                @click="resetForm"
                                :disabled="isResetting"
                            >
                                <v-icon start>mdi-refresh</v-icon>
                                重置
                            </v-btn>
                            <v-btn 
                                color="primary" 
                                @click="submitForm"
                                :loading="submitting"
                            >
                                <v-icon start>mdi-content-save</v-icon>
                                提交
                            </v-btn>
                        </v-card-actions>
                    </v-card>
                </v-container>
            </v-main>

            <!-- Snackbar 提示 -->
            <v-snackbar
                v-model="snackbar.show"
                :color="snackbar.color"
                :timeout="snackbar.timeout"
                top
            >
                {{ snackbar.text }}
                <template v-slot:actions>
                    <v-btn variant="text" @click="snackbar.show = false">关闭</v-btn>
                </template>
            </v-snackbar>
        </v-app>
    </div>

    <script>
        const { createApp } = Vue
        
        // 从 Django 模板获取数据
        const isAdmin = {{ is_admin|lower }};
        const codeOptions = {{ code_options|safe }};
        const initialCode = "{{ initial_code }}";
        const csrfToken = "{{ csrf_token }}";
        
        const app = createApp({
            data() {
                return {
                    // 管理员侧边栏状态
                    drawer: true,
                    
                    // 表单数据
                    formData: {
                        field1: '', // 产品编码
                        field2: '', // 产品名称
                        field3: '', // 规格参数
                        field4: '', // 重量
                        field5: '', // 价格
                        field6: '', // 分类
                        date_field: '' // 生产日期
                    },
                    
                    // 下拉框选择
                    selectedCode: initialCode,
                    
                    // 切换开关状态
                    isNewProduct: false,
                    
                    // 选项数据
                    codeOptions: codeOptions,
                    
                    // 加载和提交状态
                    submitting: false,
                    isResetting: false,
                    
                    // 表单验证规则
                    field1Rules: [
                        v => !!v || '产品编码不能为空'
                    ],
                    field2Rules: [
                        v => !!v || '产品名称不能为空'
                    ],
                    
                    // Snackbar 状态
                    snackbar: {
                        show: false,
                        text: '',
                        color: 'success',
                        timeout: 3000
                    },
                    
                    // 初始状态备份（用于重置）
                    initialState: {
                        formData: {
                            field1: '',
                            field2: '',
                            field3: '',
                            field4: '',
                            field5: '',
                            field6: '',
                            date_field: ''
                        },
                        selectedCode: initialCode,
                        isNewProduct: false
                    }
                }
            },
            
            methods: {
                // 下拉框选择处理
                onCodeSelect(value) {
                    this.selectedCode = value;
                    
                    if (value) {
                        // 找到选中的选项并填充详细信息
                        const selectedOption = this.codeOptions.find(option => option.value === value);
                        if (selectedOption && selectedOption.details) {
                            const details = selectedOption.details;
                            this.formData.field2 = details.field2 || '';
                            this.formData.field3 = details.field3 || '';
                            this.formData.field4 = details.field4 || '';
                            this.formData.field5 = details.field5 || '';
                            this.formData.field6 = details.field6 || '';
                            this.formData.date_field = details.date_field || '';
                        }
                    } else {
                        // 清空详细信息
                        this.clearDetailFields();
                    }
                },
                
                // 切换开关变化处理
                onRadioChange(value) {
                    this.isNewProduct = value;
                    
                    if (value) {
                        // 新建产品模式：禁用下拉框，启用第一个输入框，清空其他字段
                        this.selectedCode = null;
                        this.clearDetailFields();
                        this.formData.field1 = ''; // 清空产品编码以便输入
                    } else {
                        // 选择现有产品模式：启用下拉框，禁用第一个输入框
                        this.formData.field1 = this.selectedCode || '';
                        if (this.selectedCode) {
                            this.onCodeSelect(this.selectedCode);
                        }
                    }
                },
                
                // 清空详细信息字段
                clearDetailFields() {
                    this.formData.field2 = '';
                    this.formData.field3 = '';
                    this.formData.field4 = '';
                    this.formData.field5 = '';
                    this.formData.field6 = '';
                    this.formData.date_field = '';
                },
                
                // 字段变化处理
                onFieldChange(fieldName, value) {
                    this.formData[fieldName] = value;
                },
                
                // 日期变化处理
                onDateChange(value) {
                    this.formData.date_field = value;
                },
                
                // 提交表单
                async submitForm() {
                    // 表单验证
                    if (this.isNewProduct && !this.formData.field1) {
                        this.showSnackbar('请填写产品编码', 'error');
                        return;
                    }
                    
                    if (!this.isNewProduct && !this.selectedCode) {
                        this.showSnackbar('请选择产品', 'error');
                        return;
                    }
                    
                    if (!this.formData.field2) {
                        this.showSnackbar('请填写产品名称', 'error');
                        return;
                    }
                    
                    this.submitting = true;
                    
                    try {
                        const submitData = {
                            ...this.formData,
                            isNewProduct: this.isNewProduct,
                            selectedCode: this.selectedCode
                        };
                        
                        const response = await fetch('/api/submit-product/', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': csrfToken
                            },
                            body: JSON.stringify(submitData)
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            this.showSnackbar(result.message, 'success');
                        } else {
                            this.showSnackbar(result.error || '提交失败', 'error');
                        }
                    } catch (error) {
                        console.error('提交错误:', error);
                        this.showSnackbar('网络错误，请重试', 'error');
                    } finally {
                        this.submitting = false;
                    }
                },
                
                // 重置表单
                resetForm() {
                    this.isResetting = true;
                    
                    // 恢复初始状态
                    this.formData = { ...this.initialState.formData };
                    this.selectedCode = this.initialState.selectedCode;
                    this.isNewProduct = this.initialState.isNewProduct;
                    
                    // 如果有初始选择，重新加载详细信息
                    if (this.selectedCode && !this.isNewProduct) {
                        this.onCodeSelect(this.selectedCode);
                    }
                    
                    this.isResetting = false;
                    this.showSnackbar('表单已重置', 'info');
                },
                
                // 显示 Snackbar 提示
                showSnackbar(text, color = 'success') {
                    this.snackbar = {
                        show: true,
                        text: text,
                        color: color,
                        timeout: 3000
                    };
                }
            },
            
            mounted() {
                // 初始化 Vuetify
                const vuetify = Vuetify.createVuetify({
                    theme: {
                        defaultTheme: 'light'
                    }
                });
                
                // 如果有初始选择，加载详细信息
                if (this.selectedCode && !this.isNewProduct) {
                    this.onCodeSelect(this.selectedCode);
                }
                
                // 保存初始状态用于重置
                this.initialState = {
                    formData: { ...this.formData },
                    selectedCode: this.selectedCode,
                    isNewProduct: this.isNewProduct
                };
                
                this.$nextTick(() => {
                    app.use(vuetify);
                });
            }
        });
        
        app.mount('#app');
    </script>
</body>
</html>